package com.huicoo.forestmanager.widget.update;

import com.huicoo.forestmanager.util.LogUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownUtil implements Callback {

    private OkHttpClient mOkHttpClient;
    private DownListener downListener;
    private String downPath;
    private int lastProgress = 0;

    public DownUtil(DownListener downListener) {
        this.downListener = downListener;
        mOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    public void downFile(String downUrl, String downPath) {
        this.downPath = downPath;
        try {
            downListener.downStart();
            String downDir = downPath.substring(0, downPath.lastIndexOf("/")).trim();
            String downName = downPath.substring(downPath.lastIndexOf("/") + 1, downPath.length()).trim();
            LogUtils.v("gogogo down apk 下载地址 == " + downDir + "   下载的名字 == " + downName);
            File destDir = new File(downDir);
            if (destDir.isDirectory() && !destDir.exists()) {
                destDir.mkdirs();
            }
            Request request = new Request.Builder().url(downUrl).build();
            mOkHttpClient.newCall(request).enqueue(this);
        } catch (Exception e) {
            downListener.downFailed(e.toString());
            e.printStackTrace();
        }
    }

    public void cancelDown() {
        Dispatcher dispatcher = mOkHttpClient.dispatcher();
        for (Call call : dispatcher.runningCalls()) {
            call.cancel();
        }
    }


    @Override
    public void onFailure(Call call, IOException e) {
        downListener.downFailed(e.toString());
        e.printStackTrace();
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        File file = new File(downPath);
        LogUtils.v("gogogo download path = " + downPath);
        if (file.exists()) {
            LogUtils.v("gogogo down apk 文件存在，删除文件==");
            file.delete();
        }
        if (!file.exists()) {
            LogUtils.v("gogogo down apk 下载文件不存在创建文件== ");
            boolean isCreate = file.createNewFile();
            LogUtils.v("gogogo down apk 创建文件==" + isCreate);
        }

        InputStream is = null;
        byte[] buf = new byte[2048];
        int len;
        FileOutputStream fos = null;
        try {
            is = response.body().byteStream();
            long total = response.body().contentLength();
            fos = new FileOutputStream(file);
            long sum = 0;
            long saveSum = 0;
            while ((len = is.read(buf)) != -1) {
                fos.write(buf, 0, len);
                sum += len;
                final int progress = (int) (sum * 1.0f / total * 100);
                final long speed = sum - saveSum;
                saveSum = sum;
                LogUtils.v("gogogo down apk ===================" + progress + "  speed =" + speed);
                updateProgress(progress, speed);
            }
            fos.flush();
            downListener.downSuccess(downPath);
            LogUtils.v("gogogo down apk =================success==");
        } catch (Exception e) {
            downListener.downFailed(e.toString());
            e.printStackTrace();
        } finally {
            if (is != null)
                is.close();
            if (fos != null)
                fos.close();
        }
    }

    private void updateProgress(int progress, long speed) {
        if (progress > lastProgress) {
            downListener.downProgress(progress, speed);
        }
        lastProgress = progress;
    }


}
